<?php

Solar::loadClass('Domain51_Model_Mapper');

class Domain51_Model_Mapper_Sql extends Domain51_Model_Mapper
{
    public function fetchById($id) {
        Solar::register('sql', 'Solar_Sql');
        $select = Solar::factory('Solar_Sql_Select');
        $record = $select
            ->from($this->_metaData->table_name, $this->_metaData->columns)
            ->where("{$this->_metaData->primaryKey} = :id")
            ->bind(array('id' => $id))
            ->fetch('row');
        
        $config = array(
            'properties' => $record->toArray(),
            'meta' => $this->_metaData
        );
        
        $model = Solar::factory($this->_modelName, $config);
        $model->attach(array($this, 'save'));
        return $model;
    }
    
    public function save(Domain51_Model_Abstract $model)
    {
        if (!$model->isModified()) {
            // do nothing
            return;
        }
        
        $sql = Solar::factory('Solar_Sql', true);
        $tableName = $this->_metaData->table_name;
        
        if ($model->isNew()) {
            // we have a new record, so proceed to insert
            
            // grab the next sequence ID
            $newId = $sql->nextSequence($tableName);
            $model->id = $newId;
            $sql->insert($tableName, $model->toArray());
        } else {
            // and update
            $sql->update(
                $tableName, 
                $model->toArray(),
                array("{$tableName}.{$this->_metaData->primaryKey} = :id")
            );
        }
        
        // update from the DB in case there were defaults there what we haven't
        // loaded yet.
        $select = Solar::factory('Solar_Sql_Select');
        $record = $select
            ->from($tableName, $this->_metaData->columns)
            ->where("{$tableName}.{$this->_metaData->primaryKey} = ?", $model->id)
            ->fetch('row');
        return $record->toArray();
        
    }
}

?>